<?php

include_once '../AtacCommunicator/ACBusWaitingTimes.php';
include_once '../Model/BusStop.php';
include_once '../Utility/DebugLogs.php';
include_once '../Model/BusLinePath.php';
include_once '../Model/GPS.php';
include_once '../AtacCommunicator/ACBikesStatus.php';
include_once '../InfoManager/Constants.php';
include_once '../Utility/simplehtmldom/simple_html_dom.php';

ini_set('max_execution_time', '0'); // 0 = no limit.
ini_set("memory_limit",-1);

date_default_timezone_set('Europe/Rome');

$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
mysql_select_db(DBNAME);

$logfile = fopen($_SERVER['DOCUMENT_ROOT']."/RMob/iPhone-Server/Log/mycachelog.txt",'a');
logthis("AddNewBusStops");

$mystops=array();
$out=array();


$stops = query("select distinct fermata from ifermata_pf where fermata not in (select IMPIANTO from `ifermata_fermateAutobus`)");
$stops2 = query("select distinct fermata from ifermata_pf where fermata not in (select IMPIANTO from `ifermata_fermateAutobus`)");

foreach($stops2 as $s){
	$stops[]=$s;
}

foreach($stops as $stop){
	$found=0;
	$stop=$stop['fermata'];
	$paths = query("select pathID from ifermata_pf where fermata=$stop");
	foreach($paths as $path){
		$path=$path['pathID'];
		$link="http://muovi.roma.it/paline/mappa/static/$path?id_palina=$stop";
		$page = getHTMLPageFromURL($link);
		$html = str_get_html($page);
		//$text = $html->plaintext;
		foreach ($html->find("span[class=emph]") as $el){
			$name = $el->innertext;
		}
		foreach ($html->find("div[class=c]/a") as $el) {
			$chunks=explode("?",$el->href);
			list($dummy0,$dummy1,$dummy2,$dummy3,$dummy4,$dummy5,$lon,$lat)=explode("/",$chunks[0]);
			//print("$name - $stop ($lat,$lon)<br/><br/><br/><br/><br/>");
			if(!empty($lat) && !empty($lon) && !empty($name)){
				if(!in_array($stop,$mystops)){
					$mystops[]=$stop;
    			$addressurl = "http://maps.google.com/maps/geo?q=".$lat.",".$lon."&output=json";
    			$info = json_decode(getHTMLPageFromURL($addressurl));
    			$address=(string)$info->Placemark[0]->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->Locality->Thoroughfare->ThoroughfareName;
					if(empty($address))
    				$address=(string)$info->Placemark->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->Locality->Thoroughfare->ThoroughfareName;
					if(empty($address)){
    				$address=(string)$info->Placemark->address;
    				$chunksaddress = explode(",",$address);
						$address = $chunksaddress[0];
					}
					if(empty($address)){
    				$address=(string)$info->Placemark[0]->address;
    				$chunksaddress = explode(",",$address);
						$address = $chunksaddress[0];
					}
					$address = str_replace(",","",$address);
					$out[]=array("IMPIANTO"=>$stop, "NOMEFERM"=>addslashes(trim(strtoupper(htmlspecialchars_decode($name,ENT_QUOTES)))),"LAT"=>$lat, "LONG"=>$lon, "ADDRESS"=>addslashes(trim(strtoupper(htmlspecialchars_decode($address,ENT_QUOTES)))));
				}
			}
		}
	}
}

foreach($out as $o)
	query("insert ignore into ifermata_fermateAutobus set IMPIANTO='$o[IMPIANTO]',NOMEFERM='$o[NOMEFERM]', LAT=$o[LAT], ifermata_fermateAutobus.LONG=$o[LONG], ADDRESS='$o[ADDRESS]'");

logthis(print_r($out,true));

function getHTMLPageFromURL($url) {
	// create curl resource
	//echo "<br>Prima di curl_init:".date("l F d, Y, h:i:s"); 
	$AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1';
	$output = "";
	
	$ch = curl_init(); 
	
	// set url 
	curl_setopt($ch, CURLOPT_URL, $url); 
	curl_setopt($ch, CURLOPT_USERAGENT, $AGENT);
	//return the transfer as a string 
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	
	// $output contains the output string 
	$output = curl_exec($ch); 
	
	// close curl resource to free up system resources 
	curl_close($ch);
	
	unset($ch);
	
	//$output = file_get_contents($url); 
	
	
	return $output;
}

function query($query)
{ 
	global $conn;
  $a = array();
  $ris = mysql_query($query,$conn);
  $mysqlerrno = mysql_errno($conn); 
  if ($mysqlerrno != 0)
  { 
    return false;
  }
  else if ($ris === true)
    return true;
  else
    while ($row = mysql_fetch_array($ris,MYSQL_ASSOC))
      $a[] = $row;
  return $a;  
}

function is_utf8($string) {
  return (preg_match('/^([\x00-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xec][\x80-\xbf]{2}|\xed[\x80-\x9f][\x80-\xbf]|[\xee-\xef][\x80-\xbf]{2}|f0[\x90-\xbf][\x80-\xbf]{2}|[\xf1-\xf3][\x80-\xbf]{3}|\xf4[\x80-\x8f][\x80-\xbf]{2})*$/', $string) === 1);
}

function utf8($s)
{ return is_utf8($s)?$s:utf8_encode($s);
}


?>